package mall.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import mall.pojo.Cart;
import mall.pojo.Category;
import mall.pojo.Product;
import mall.pojo.Shop;
import mall.service.CategoryService;
import mall.service.ProductService;
import mall.service.ShopService;
import mall.util.UtilityClass;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
@SessionAttributes("shopId")
@Scope("request")
public class ProductController {

	@Autowired
	private ProductService productService;

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private ServletContext servletContext;

	@Autowired
	private ShopService shopService;

	@Autowired
	private Cart cart;

	@RequestMapping(value ="/index-shop",method = RequestMethod.GET)
	public ModelAndView listProductShop(Map<String, Object> map,
			@RequestParam("shopid") int shopId, @RequestParam("catid") int catId) {
		ModelAndView modelAndView = new ModelAndView();
		List<Category> listCategory = categoryService.getCategoryShop(shopId);
		if (catId == -1 && listCategory.size() > 0)
			catId = listCategory.get(0).getId();
		List<Product> listNewProductShop = productService.getProductShop(
				shopId, catId, 1); // get new
		List<Product> listFeatureProductShop = productService.getProductShop(
				shopId, catId, 2); // get feature
		map.put("newproducts", listNewProductShop);
		map.put("featureproducts", listFeatureProductShop);
		map.put("listcategory", listCategory);
		map.put("cart", cart);
		modelAndView.addObject("shopId", shopId);
		modelAndView.setViewName(UtilityClass.VIEW_SHOP_INDEX);
		return modelAndView;
	}
	@RequestMapping(value="/home-shop",method=RequestMethod.GET )
	public ModelAndView homeShop(HttpSession session){
		ModelAndView modelAndView = new ModelAndView();
		int shopId = Integer
				.parseInt(session.getAttribute("shopId").toString());
		List<Category> listCategory = categoryService.getCategoryShop(shopId);
		if	(listCategory.size() > 0){
		int catId=listCategory.get(0).getId();
		List<Product> listNewProductShop = productService.getProductShop(
				shopId, catId, 1); // get new
		List<Product> listFeatureProductShop = productService.getProductShop(
				shopId, catId, 2); // get feature
		modelAndView.addObject("newproducts", listNewProductShop);
		modelAndView.addObject("featureproducts", listFeatureProductShop);
		modelAndView.addObject("listcategory", listCategory);
		modelAndView.addObject("cart", cart);
		}
		modelAndView.setViewName(UtilityClass.VIEW_SHOP_INDEX);
		return modelAndView;
	}

	@RequestMapping(value = "/preview", method = RequestMethod.GET)
	public ModelAndView productDetail(HttpSession session, 
			@RequestParam("id") int productId) {
		ModelAndView modelAndView =new ModelAndView();
		Product product = productService.getProduct(productId);
		int shopId = Integer
				.parseInt(session.getAttribute("shopId").toString());
		List<Category> listCategory = categoryService.getCategoryShop(shopId);
		modelAndView.addObject("product", product);
		modelAndView.addObject("listcategory", listCategory);
		modelAndView.setViewName(UtilityClass.VIEW_SHOP_PREVIEW);
		return modelAndView;
	}

	@RequestMapping(value = "/manage-shop-pro", method = RequestMethod.GET)
	public String listProduct(Map<String, Object> map,
			@RequestParam("id") int catId, HttpSession session) {
		int shopId = Integer
				.parseInt(session.getAttribute("shopId").toString());
		List<Category> listCategory = categoryService.getCategoryShop(shopId);
		String categoryName = "";
		if (listCategory.size() > 0) {
			if (catId == -1) {
				catId = listCategory.get(0).getId();
				categoryName = listCategory.get(0).getName();
			} else {
				categoryName = categoryService.getCategory(catId).getName();
			}
		}
		List<Product> listNewProductShop = productService.getProductShop(
				shopId, catId, 1); // get new
		List<Product> listFeatureProductShop = productService.getProductShop(
				shopId, catId, 2); // get feature

		map.put("newproducts", listNewProductShop);
		map.put("featureproducts", listFeatureProductShop);
		map.put("listcategory", listCategory);
		map.put("categoryname", categoryName);
		return UtilityClass.VIEW_SHOP_PRODUCT_ADMIN;
	}

	@RequestMapping(value = "/addproduct", method = RequestMethod.GET)
	public ModelAndView product(Map<String, Object> map, HttpSession session) {
		int shopId = Integer
				.parseInt(session.getAttribute("shopId").toString());
		List<Category> listCategory = categoryService.getCategoryShop(shopId);
		map.put("listcategory", listCategory);
		return new ModelAndView(UtilityClass.VIEW_SHOP_ADD_PRODUCT_ADMIN,
				"product", new Product());
	}

	@RequestMapping(value = "/addproduct", method = RequestMethod.POST)
	public String addProduct(@ModelAttribute("product") Product product,
			BindingResult bindingResult, HttpSession session) {
		String dirPath = "";
		String fileName = "";
		if (!bindingResult.hasErrors()) {
			FileOutputStream outputStream = null;
			// filePath = servletContext.getRealPath("/")+"resources\\data\\";
			dirPath = servletContext.getInitParameter("directory-path");
			fileName = UtilityClass.generateUniqueFileName()
					+ product.getFile().getOriginalFilename();
			try {
				outputStream = new FileOutputStream(
						new File(dirPath + fileName));
				outputStream.write(product.getFile().getFileItem().get());
				outputStream.close();
			} catch (Exception e) {
				System.out.println("Error while saving file");
				return UtilityClass.VIEW_MALL_CREATESHOP; // return createshop
															// and display error
			}
		}
		product.setDate(new Date());

		product.setPicture(servletContext.getInitParameter("uploaded-file")
				+ fileName);
		int shopId = Integer
				.parseInt(session.getAttribute("shopId").toString());
		Shop shop = shopService.getShop(shopId);
		product.setShop(shop);
		productService.createProduct(product);
		return UtilityClass.VIEW_SHOP_ADD_PRODUCT_ADMIN;
	}

	// load product info and send to view
	@RequestMapping(value = "/updateproduct", method = RequestMethod.GET)
	public ModelAndView editProduct(@RequestParam("id") int productId,
			HttpSession session) {
		ModelAndView modelAndView = new ModelAndView();
		int shopId = Integer
				.parseInt(session.getAttribute("shopId").toString());
		List<Category> listCategory = categoryService.getCategoryShop(shopId);
		Product product = productService.getProduct(productId);
		modelAndView.addObject("listcategory", listCategory);
		modelAndView.addObject("product", product);
		modelAndView.setViewName(UtilityClass.VIEW_SHOP_UPDATE_PRODUCT_ADMIN);
		return modelAndView;
	}

	// save updated product info
	@RequestMapping(value = "/updateproduct", method = RequestMethod.POST)
	public ModelAndView updateProduct(
			@ModelAttribute("product") Product product,
			BindingResult bindingResult, HttpSession session) {
		ModelAndView modelAndView = new ModelAndView();
		productService.updateProduct(product);

		// data for display product
		int shopId = Integer
				.parseInt(session.getAttribute("shopId").toString());
		List<Category> listCategory = categoryService.getCategoryShop(shopId);
		int catId = listCategory.get(0).getId();
		String categoryName = listCategory.get(0).getName();

		List<Product> listNewProductShop = productService.getProductShop(
				shopId, catId, 1); // get new
		List<Product> listFeatureProductShop = productService.getProductShop(
				shopId, catId, 2); // get feature

		modelAndView.addObject("newproducts", listNewProductShop);
		modelAndView.addObject("featureproducts", listFeatureProductShop);
		modelAndView.addObject("listcategory", listCategory);
		modelAndView.addObject("categoryname", categoryName);
		modelAndView.setViewName(UtilityClass.VIEW_SHOP_PRODUCT_ADMIN);
		return modelAndView;
	}

	@RequestMapping(value = "/delproduct", method = RequestMethod.GET)
	public ModelAndView deleteProduct(@ModelAttribute("id") int productId,
			BindingResult bindingResult, HttpSession session) {
		ModelAndView modelAndView = new ModelAndView();
		productService.deleteProduct(productId);
		// data for display product
		int shopId = Integer
				.parseInt(session.getAttribute("shopId").toString());
		List<Category> listCategory = categoryService.getCategoryShop(shopId);
		int catId = listCategory.get(0).getId();
		String categoryName = listCategory.get(0).getName();

		List<Product> listNewProductShop = productService.getProductShop(
				shopId, catId, 1); // get new
		List<Product> listFeatureProductShop = productService.getProductShop(
				shopId, catId, 2); // get feature

		modelAndView.addObject("newproducts", listNewProductShop);
		modelAndView.addObject("featureproducts", listFeatureProductShop);
		modelAndView.addObject("listcategory", listCategory);
		modelAndView.addObject("categoryname", categoryName);
		modelAndView.setViewName(UtilityClass.VIEW_SHOP_PRODUCT_ADMIN);
		return modelAndView;
	}

}
